package com.higgins.eventtracking.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class AssetTracking implements EntryPoint {
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	private final AssetTrackingServiceAsync assetTrackingService = GWT
			.create(AssetTrackingService.class);

	
	private final Button sendButton = new Button("Add");
	private final TextBox amountTextBox = new TextBox();
	private final ListBox accountTypeListBox = new ListBox();
	private final ListBox accountListBox = new ListBox();
	private final ListBox accountRepaymentListBox = new ListBox();
	private final TextBox monthlyRepaymentTextBox = new TextBox();
	private final TextBox monthlyInterestTextBox = new TextBox();
	private final Label totalAssetAmountLabel = new Label();
	private final Label errorLabel = new Label();
	private final DialogBox dialogBox = new DialogBox();
	private final Button closeButton = new Button("Close");
	private final Label textToServerLabel = new Label();
	private final HTML serverResponseLabel = new HTML();
	
	
	public void onModuleLoad() {
		setUpMainPage();
		setUpDialogBox();
		setUpHandlers();
		requestTotalAssetAmount();		
	}
	
	private void setUpMainPage()	{
		amountTextBox.setText("0.0");
		populateOutgoingListBox();
		sendButton.addStyleName("sendButton");

		RootPanel.get("amountTextBox").add(amountTextBox);
		RootPanel.get("accountTypeListBox").add(accountTypeListBox);
		RootPanel.get("accountListBox").add(accountListBox);
		RootPanel.get("accountRepaymentListBox").add(accountRepaymentListBox);
		RootPanel.get("monthlyRepaymentTextBox").add(monthlyRepaymentTextBox);
		RootPanel.get("sendButton").add(sendButton);
		RootPanel.get("totalAssetAmountLabel").add(totalAssetAmountLabel);
		RootPanel.get("monthlyInterestTextBox").add(monthlyInterestTextBox);
	}
	private void populateOutgoingListBox()	{
		accountTypeListBox.addItem("------");
		accountTypeListBox.addItem("Cash");
		accountTypeListBox.addItem("Loan");
		
		accountListBox.addItem("------");
		accountListBox.addItem("Silver");
		accountListBox.addItem("Vantage");
		accountListBox.addItem("Porsche");
		accountListBox.addItem("Tax");
		accountListBox.addItem("HMRC");
		accountListBox.addItem("Tesco");
		accountListBox.addItem("Car Insurance");
		
		accountRepaymentListBox.addItem("------");
		accountRepaymentListBox.addItem("Silver");
		accountRepaymentListBox.addItem("Vantage");
		accountRepaymentListBox.addItem("Porsche");
		accountRepaymentListBox.addItem("Tax");
		accountRepaymentListBox.addItem("HMRC");
		accountRepaymentListBox.addItem("Tesco");
		accountRepaymentListBox.addItem("Car Insurance");
	}
	
	private void setUpDialogBox()	{
		// Create the popup dialog box
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});
	}
	
	private void setUpHandlers()	{
		class MyHandler implements ClickHandler, KeyUpHandler {
			public void onClick(ClickEvent event) {
				sendAssetToServer();
			}

			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) 
					sendAssetToServer();
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendAssetToServer() {
				// First, we validate the input.
				errorLabel.setText("");
				sendButton.setEnabled(false);
				if (accountTypeListBox.getItemText(accountTypeListBox.getSelectedIndex()).equals("Cash"))
					sendCashToServer();
				else if (accountTypeListBox.getItemText(accountTypeListBox.getSelectedIndex()).equals("Loan"))
					sendLoanToServer();
			}
			
			private void sendCashToServer()	{
				assetTrackingService.addAsset(amountTextBox.getText(), 
						accountListBox.getValue(accountListBox.getSelectedIndex()),
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								dialogBox.setText("Remote Procedure Call - Failure");
								serverResponseLabel.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								dialogBox.center();
								dialogBox.setPopupPosition(0, 0);
								closeButton.setFocus(true);
							}

							public void onSuccess(String result) {
								dialogBox.setText("Remote Procedure Call");
								serverResponseLabel.removeStyleName("serverResponseLabelError");
								dialogBox.center();
								dialogBox.setPopupPosition(0, 0);
								closeButton.setFocus(true);
								requestTotalAssetAmount();
							}
						});
			}
			private void sendLoanToServer()	{
				assetTrackingService.addAsset(amountTextBox.getText(), 
						accountListBox.getValue(accountListBox.getSelectedIndex()),
						accountRepaymentListBox.getValue(accountRepaymentListBox.getSelectedIndex()),
						monthlyRepaymentTextBox.getText(),
						monthlyInterestTextBox.getText(),
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								dialogBox.setText("Remote Procedure Call - Failure");
								serverResponseLabel.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								dialogBox.center();
								dialogBox.setPopupPosition(0, 0);
								closeButton.setFocus(true);
							}

							public void onSuccess(String result) {
								dialogBox.setText("Remote Procedure Call");
								serverResponseLabel.removeStyleName("serverResponseLabelError");
								dialogBox.center();
								dialogBox.setPopupPosition(0, 0);
								closeButton.setFocus(true);
								requestTotalAssetAmount();
							}
						});
			}			
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);		
	}
	
	private void requestTotalAssetAmount()	{
		assetTrackingService.retrieveTotalAssetAmount(
				new AsyncCallback<String>() {
					public void onFailure(Throwable caught) {
						// Show the RPC error message to the user
						dialogBox.setText("Remote Procedure Call - Failure");
						serverResponseLabel.addStyleName("serverResponseLabelError");
						serverResponseLabel.setHTML(SERVER_ERROR);
						dialogBox.center();
						dialogBox.setPopupPosition(0, 0);
						closeButton.setFocus(true);
					}

					public void onSuccess(String result) {
						totalAssetAmountLabel.setText(result);
					}
				});
	}
}
